package com.ruoyi.web.controller.common;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class CommonUtils
{
    /**
     *  获取请求的IP地址， https://ip.useragentinfo.com/json?ip=117.136.12.79  IP地址归属地查询
     * @param request
     * @return
     */
    public static String getIpAddress(HttpServletRequest request)
    {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if  ("127.0.0.1".equals(ip)||ip=="127.0.0.1"||"0:0:0:0:0:0:0:1".equals(ip)||ip=="0:0:0:0:0:0:0:1") {
            try
            {
                ip = InetAddress.getLocalHost().getHostAddress();
            } catch (UnknownHostException e)
            {
                e.printStackTrace();
            }
        }
        return ip;
    }
}
